package com.zcs.app.lucky.ui

import android.view.View
import cn.sxw.android.base.dialog.CustomDialogHelper
import cn.sxw.android.base.kt.BaseViewModel
import com.safframework.delegate.extras.extraDelegate
import com.zcs.app.lucky.adapter.ResultAdapterHelper
import com.zcs.app.lucky.base.BaseLuckyActivity
import com.zcs.app.lucky.data.LuckyDataCache
import com.zcs.app.lucky.databinding.ActivityLuckyResultBinding

class LuckyResultActivity : BaseLuckyActivity<ActivityLuckyResultBinding, BaseViewModel>() {
    override fun needViewModel(): Boolean = false
    private val mId by extraDelegate(KEY_ID, "")
    private val canDelete by extraDelegate(KEY_BOOLEAN, true)
    private val resultAdapterHelper by lazy {
        ResultAdapterHelper()
    }

    // 懒加载机制
    override fun isLazyInit() = true
    private val mLucky by lazy {
        LuckyDataCache.findByIdOrNewInstance(mId)
    }

    // 程序已就绪
    override fun onReady() {
        binding.toolbar.tvToolbarTitle.text = "抽奖结果查看"
        binding.loadingLayout.visibility = View.VISIBLE
        if (canDelete)
            binding.toolbar.tvToolbarRight.text = "删除"
    }

    override fun onInit() {
        // 初始UI
        initView()
        // 初始化数据
        initData()
        // 初始化观察者
        initObserve()
    }

    override fun initObserve() {
    }

    override fun initData() {
        // 展示抽奖人员
        mLucky.resultList.sortWith { r1, r2 ->
            r1.prize!!.level!!.id.compareTo(r2.prize!!.level!!.id)
        }

        resultAdapterHelper.mItems.clear()
        resultAdapterHelper.mItems.addAll(mLucky.resultList)
        resultAdapterHelper.initAdapter(binding.rvResult) {}
        // 信息
        binding.tvName.text = mLucky.name
        binding.tvDesc.text = mLucky.desc
        binding.tvLuckyTime.text = mLucky.niceTime()
        binding.tvGroupName.text = mLucky.group!!.niceName()
        hideLoading()
    }

    override fun initView() {
    }

    override fun hideLoading() {
        super.hideLoading()
        binding.loadingLayout.visibility = View.GONE
    }

    override fun addOnClickListener() {
        binding.toolbar.ivToolbarBack.setOnClickListener { onBackPressed() }
        if (canDelete) {
            binding.toolbar.tvToolbarRight.setOnClickListener {
                CustomDialogHelper.showCustomConfirmDialog(
                    this,
                    "你确定要删除这条记录吗？",
                    object : CustomDialogHelper.NativeDialogCallback {
                        override fun onConfirm() {
                            LuckyDataCache.removeById(mId, true)
                            showToast("删除成功")
                            killMyself()
                        }

                        override fun onCancel() {
                        }
                    })
            }
        }
    }
}